package cn.picclife.mwx.manager.sys.controller;

import cn.picclife.mwx.common.core.util.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import cn.picclife.mwx.common.core.util.crypto.PasswordHashUtil;
//import cn.picclife.mwx.common.web.controller.ApiBaseController;
import cn.picclife.mwx.manager.base.BaseResult1;
import cn.picclife.mwx.manager.sys.model.bo.BranchDataAuthBo;
import cn.picclife.mwx.manager.sys.model.bo.CommonBo;
import cn.picclife.mwx.manager.sys.model.bo.LoginValidateBo;
import cn.picclife.mwx.manager.sys.model.bo.OperatorMenuInfo;
import cn.picclife.mwx.manager.sys.model.bo.PageCount;
import cn.picclife.mwx.manager.sys.model.bo.User;
import cn.picclife.mwx.manager.sys.model.bo.UserSessionBo;
import cn.picclife.mwx.manager.sys.model.po.Enum;
import cn.picclife.mwx.manager.sys.model.po.Operator;
import cn.picclife.mwx.manager.sys.service.UserMgMtService;
import cn.picclife.mwx.manager.util.Captcha;
import cn.picclife.mwx.manager.util.RestUtils;
import cn.picclife.mwx.manager.util.uniqueseq.UniqueSeq;

/**
 * @ClassName: UserCtroller
 * @Description:后台管理用户控制层
 * @author hui
 * @date: 2016年12月5日 下午3:43:53 
 */
@Controller
@RequestMapping("/api")
public class UserMgMtApiController /*extends ApiBaseController*/ {
	private Log log = LogFactory.getLog(UserMgMtApiController.class);
	@Autowired
	private UserMgMtService userMgMtService;

	/**
	 * @Title: redirect
	 * @Description: 登录验证
	 * @param req
	 * @param res
	 * @return
	 * @throws Exception
	 * @author hui
	 * @date: 2016年12月5日 下午3:46:20
	 */
	@RequestMapping("/user/login_user")
	@ResponseBody
	public BaseResult1 login(HttpServletRequest req, HttpServletResponse res, LoginValidateBo loginValidateBo)
			throws Exception {
		String message = "";// 提示消息
		String opt_no = loginValidateBo.getOptNo();
		String validateCode = loginValidateBo.getValidateCode();
		char[] opt_password = loginValidateBo.getPassword();

		BaseResult1 result = new BaseResult1();
		
		// 判断用户名是否为空
		if (StringUtils.isBlank(opt_no)) {
			message = "用户名不能为空";
			result.setRet(BaseResult1.BIZ_ERROR);
			result.setMsg(message);
			RestUtils.error(res, result);
			return null;
		}
		// 判断密码是否为空
		if (null == opt_password || StringUtils.isBlank(String.valueOf(opt_password))) {
			message = "密码不能为空";
			result.setRet(BaseResult1.BIZ_ERROR);
			result.setMsg(message);
			RestUtils.error(res, result);
			return null;
		}
		// 判断验证码是否为空
		if (StringUtils.isBlank(validateCode)) {
			message = "验证码不能为空";
			result.setRet(BaseResult1.BIZ_ERROR);
			result.setMsg(message);
			RestUtils.error(res, result);
			return null;
		}
		// 判断验证码是否正确
//		String imageCode = (String) req.getSession().getAttribute("imageCode");
//		if (!validateCode.equalsIgnoreCase(imageCode)) {
//			message = "验证码错误";
//			result.setRet(BaseResult1.BIZ_ERROR);
//			result.setMsg(message);
//			RestUtils.error(res, result);
//			return null;
//		}
		// 判断用户名密码是否匹配
		Operator operator = new Operator();
		operator = userMgMtService.selectByOptnoAndPwd(opt_no, opt_password);
		 if (operator == null) {
			message = "用户名或密码错误";
			result.setRet(BaseResult1.BIZ_ERROR);
			result.setMsg(message);
			RestUtils.error(res, result);
			return null;
		}
		 UserSessionBo userSessionBo = userMgMtService.queryBranchByOptNo(opt_no);//获取用户机构信息
		if (userSessionBo == null) {
			message = "用户信息获取失败";
			result.setRet(BaseResult1.BIZ_ERROR);
			result.setMsg(message);
			RestUtils.error(res, result);
			return null;
		} 
		HttpSession session = req.getSession();
		List<OperatorMenuInfo> userMenuList = userMgMtService.queryUserMenuList(operator);
		session.setAttribute("menuList", userMenuList);
		session.setAttribute("user", userSessionBo);
		log.info("session里面存储的用户信息："+ JsonUtils.ObjectToJson(session.getAttribute("user")));
		result.setRet(BaseResult1.SUCCESS);
		result.setMsg("登录成功");
		return result;
	}
	/**
	 * @Title: queryUserAuth
	 * @Description: 查询用户权限
	 * @param req
	 * @param res
	 * @return
	 * @author hui
	 * @date: 2016年12月6日 下午2:39:11
	 */
	@RequestMapping("/user/query_user_auth")
	@ResponseBody
	public User queryUserAuth(HttpServletRequest req, HttpServletResponse res) {
		HttpSession session = req.getSession();
		UserSessionBo userSessionBo = (UserSessionBo) session.getAttribute("user");
		BaseResult1 result = new BaseResult1();
		String optNo=userSessionBo.getOptNo();
		Operator operator = userMgMtService.getUserDetail(optNo);
		if(operator != null){
			List<OperatorMenuInfo> userMenuList = (List<OperatorMenuInfo>) session.getAttribute("menuList");
			User user = new User();
			user.setOperator(operator);
			user.setMenuList(userMenuList);
			return user;
		} else {
			result.setRet(BaseResult1.BIZ_ERROR);
			result.setMsg("用户信息获取失败");
			RestUtils.error(res, result);
			return null;
		}
		
	}
	/**
	 * @Title: queryUser
	 * @Description: 查询用户
	 * @param req
	 * @param res
	 * @return
	 * @author hui
	 * @date: 2016年12月6日 下午2:39:11
	 */
	@RequestMapping("/user/query_user")
	@ResponseBody
	public PageCount queryUser(HttpServletRequest req, HttpServletResponse res, PageCount pageCount) {
		BaseResult1 baseResult = new BaseResult1();
		UserSessionBo userSessionBo = (UserSessionBo) req.getSession().getAttribute("user");
		String optNo=userSessionBo.getOptNo();
		String deptNo=userSessionBo.getDeptNo();
		if(pageCount.getObject() == null){
			pageCount.setObject(new HashMap<String,Object>());
		}
		pageCount.getObject().put("userNo", optNo);
		pageCount.getObject().put("deptNo", deptNo);
		pageCount = userMgMtService.queryUser(req, res, pageCount);
		if (pageCount != null) {
			return pageCount;
		} else {
			baseResult.setRet(BaseResult1.BIZ_ERROR);
			baseResult.setMsg("获取用户失败");
			RestUtils.error(res, baseResult);
			return null;
		}
	}

	/**
	 * @Title: addUser
	 * @Description: 新增用户
	 * @param req
	 * @param res
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws UnsupportedEncodingException
	 * @author hui
	 * @date: 2016年12月6日 下午5:30:40
	 */
	@RequestMapping("/user/add_user")
	@ResponseBody
	public BaseResult1 addUser(HttpServletRequest req, HttpServletResponse res, Operator user) {
		UserSessionBo userSessionBo = (UserSessionBo) req.getSession().getAttribute("user");
		BaseResult1 result = new BaseResult1();
		
		if (StringUtils.isBlank(user.getDeptNo())) {
			result.setRet(BaseResult1.BIZ_ERROR);
			result.setMsg("组织机构不能为空");
			RestUtils.error(res, result);
			return null;
		}
		if (StringUtils.isBlank(user.getOptNo())) {
			result.setRet(BaseResult1.BIZ_ERROR);
			result.setMsg("用户登录名不能为空");
			RestUtils.error(res, result);
			return null;
		}
		if (StringUtils.isBlank(user.getOptName())) {
			result.setRet(BaseResult1.BIZ_ERROR);
			result.setMsg("用户姓名不能为空");
			RestUtils.error(res, result);
			return null;
		}
		if (StringUtils.isBlank(user.getOptType())) {
			result.setRet(BaseResult1.BIZ_ERROR);
			result.setMsg("用户类型不能为空");
			RestUtils.error(res, result);
			return null;
		}
		if (null == user.getOptPassword() || StringUtils.isBlank(String.valueOf(user.getOptPassword()))) {
			result.setRet(BaseResult1.BIZ_ERROR);
			result.setMsg("用户密码不能为空");
			RestUtils.error(res, result);
			return null;
		}
		if (null == user.getOptPasswordT() || StringUtils.isBlank(String.valueOf(user.getOptPasswordT()))) {
			result.setRet(BaseResult1.BIZ_ERROR);
			result.setMsg("确认密码不能为空");
			RestUtils.error(res, result);
			return null;
		}
		if (!Arrays.equals(user.getOptPassword(),user.getOptPasswordT())) {
			result.setRet(BaseResult1.BIZ_ERROR);
			result.setMsg("两次密码不一致");
			RestUtils.error(res, result);
			return null;
		}
		
		String optNo=userSessionBo.getOptNo();
		Long serno = UniqueSeq.getUniqueSeq("opt_id", "t_operator");
		user.setOptId(serno.toString());
		Date date = new Date();
		user.setStartDate(date);
		try {
			user.setEndDate(DateUtils.parseDateStrictly("9999-09-09", "yyyy-MM-dd"));
		} catch (ParseException e) {
			log.error(e);
		}
		char[] pwd=PasswordHashUtil.createHash(user.getOptPassword()).toCharArray();//将密码加密
		user.setOptPassword(pwd);
		user.setCrtDate(date);
		user.setMdfDate(date);
		user.setDataFlag("1");
		user.setOptStatus("1");
		user.setCrtUser(optNo);
		user.setMdfUser(optNo);
		try {
			int row = userMgMtService.addUser(req, res, user);
	        Arrays.fill(pwd, ' ');
			if (row > 0) {
				result.setRet(BaseResult1.SUCCESS);
				return result;
			} else {
				result.setRet(BaseResult1.BIZ_ERROR);
				result.setMsg("新增用户失败");
				RestUtils.error(res, result);
				return null;
			}
		} catch (Throwable t) {
			result.setRet(BaseResult1.SYS_ERROR);
			result.setMsg("新增用户失败");
			RestUtils.error(res, result);
			return null;
		}
	}

	/**
	 * @Title: addUser
	 * @Description: 删除用户
	 * @param req
	 * @param res
	 * @param user
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws UnsupportedEncodingException
	 * @author hui
	 * @date: 2016年12月6日 下午5:51:21
	 */
	@RequestMapping("/user/delete_user")
	@ResponseBody
	public BaseResult1 deleteUser(HttpServletRequest req, HttpServletResponse res, CommonBo commonBo) {
		BaseResult1 result = new BaseResult1();
		if(commonBo.getDatas().size()<1){
			result.setRet(BaseResult1.BIZ_ERROR);
			result.setMsg("请至少选择一个用户");
			RestUtils.error(res, result);
			return result;
		}
		try {
			int row = userMgMtService.deleteUser(req, res, commonBo);
			if (row > 0) {
				result.setRet(BaseResult1.SUCCESS);
				result.setMsg("删除成功");
				return result;
			} else {
				result.setRet(BaseResult1.BIZ_ERROR);
				result.setMsg("删除失败");
				RestUtils.error(res, result);
				return null;
			}
		} catch (Exception e) {
			log.error(e);
			result.setRet(BaseResult1.SYS_ERROR);
			result.setMsg("删除失败");
			RestUtils.error(res, result);
			return null;
		}
	}

	/**
	 * @Title: addUser
	 * @Description: 修改用户信息
	 * @param req
	 * @param res
	 * @param
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws UnsupportedEncodingException
	 * @author hui
	 * @date: 2016年12月6日 下午5:51:21
	 */
	@RequestMapping("/user/modify_user")
	@ResponseBody
	public BaseResult1 modifyUser(HttpServletRequest req, HttpServletResponse res, Operator operator) {
		BaseResult1 result = new BaseResult1();
		UserSessionBo userSessionBo = (UserSessionBo) req.getSession().getAttribute("user");

		String optNo=userSessionBo.getOptNo();
		operator.setMdfDate(new Date());
		operator.setMdfUser(optNo);
		if(null != operator.getOptPassword() && !StringUtils.isBlank(String.valueOf(operator.getOptPassword()))){
			operator.setOptPassword(PasswordHashUtil.createHash(operator.getOptPassword()).toCharArray());
		}
		try {
			int row = userMgMtService.modifyUser(req, res, operator);
			if (row > 0) {
				result.setRet(BaseResult1.SUCCESS);
				return result;
			} else {
				result.setRet(BaseResult1.BIZ_ERROR);
				result.setMsg("修改用户信息失败");
				RestUtils.error(res, result);
				return null;
			}
		} catch (Throwable t) {
			result.setRet(BaseResult1.SYS_ERROR);
			result.setMsg("修改用户信息失败");
			RestUtils.error(res, result);
			return null;
		}
	}

	@RequestMapping("/user/add_user_role")
	@ResponseBody
	public BaseResult1 addUserRole(HttpServletRequest req, HttpServletResponse res, CommonBo commonBo) {
		BaseResult1 result = new BaseResult1();
		UserSessionBo userSessionBo = (UserSessionBo) req.getSession().getAttribute("user");
		String optNo=userSessionBo.getOptNo();
		int count = userMgMtService.addRoleUser(commonBo, optNo);
		if (count > 0) {
			result.setRet(BaseResult1.SUCCESS);
			result.setMsg("保存成功");
			return result;
		} else {
			result.setRet(BaseResult1.BIZ_ERROR);
			result.setMsg("保存失败");
			RestUtils.error(res, result);
			return null;
		}
	}

	@RequestMapping("/user/add_user_data_auth")
	@ResponseBody
	public BaseResult1 addUserDataAuth(HttpServletRequest req, HttpServletResponse res,
			CommonBo commonBo) {
		BaseResult1 result = new BaseResult1();
		UserSessionBo userSessionBo = (UserSessionBo) req.getSession().getAttribute("user");
		String optNo=userSessionBo.getOptNo();
		int count = userMgMtService.addUserDataAuth(commonBo, optNo);
		if (count > 0||count == -1) {
			result.setRet(BaseResult1.SUCCESS);
			result.setMsg("保存成功");
			return result;
		} else {
			result.setRet(BaseResult1.BIZ_ERROR);
			result.setMsg("保存失败");
			RestUtils.error(res, result);
			return null;
		}
		
		
	}

	/**
	 * @Title: getUserBranch
	 * @Description: 获取用户机构树
	 * @param req
	 * @param res
	 * @param branchId
	 *           机构id
	 * @return
	 * @author hui
	 * @date: 2016年12月12日 下午4:50:13
	 */
	@RequestMapping("/user/get_user_branch")
	@ResponseBody
	public List<BranchDataAuthBo> getUserBranch(HttpServletRequest req, HttpServletResponse res, String branchId) {
		UserSessionBo userSessionBo = (UserSessionBo) req.getSession().getAttribute("user");
		boolean isStub=true;
		if(branchId==null||branchId.equals("")){
			branchId=userSessionBo.getDeptNo();
			isStub=false;
		}else{
			log.info("机构查询的branchId"+branchId);
		}
		log.info("isStub的值为"+isStub);
		List<BranchDataAuthBo> userDeptList = userMgMtService.queryUserDeptListByOptno(branchId,isStub);
		return userDeptList;
	}

	
	
	
	
	
	
	
	@RequestMapping("/user/get_user_branch_auth")
	@ResponseBody
	public List<BranchDataAuthBo> getUserBranchAuth(HttpServletRequest req, HttpServletResponse res, String branchId) {
		UserSessionBo userSessionBo = (UserSessionBo) req.getSession().getAttribute("user");
		String opt_no = req.getParameter("optNo");
		boolean isStub=true;
		if(branchId==null||branchId.equals("")){
			branchId=userSessionBo.getDeptNo();
			isStub=false;
		}
		List<BranchDataAuthBo> userDeptList = userMgMtService.queryUserDeptListByOptnoAuth(branchId,isStub,opt_no);
		return userDeptList;
	}

	
	
	
	
	
	
	
	/**
	 * @Title: sendValidateCode
	 * @Description: 生成登录页面验证码
	 * @param req
	 * @param res
	 * @throws IOException
	 * @author hui
	 * @date: 2016年12月14日 下午2:27:40
	 */
	@RequestMapping("/user/get_user_code")
	public void getValCode(HttpServletRequest request, HttpServletResponse response) throws Exception {
		OutputStream os = response.getOutputStream();
		HttpSession session = request.getSession();
		response.setContentType("image/png");
		response.setHeader("Cache-Control", "no-cache, no-store");
		response.setHeader("Pragma", "no-cache");
		long time = System.currentTimeMillis();
		response.setDateHeader("Last-Modified", time);
		response.setDateHeader("Date", time);
		response.setDateHeader("Expires", time);
		String captcha = Captcha.getCaptchaAndWriteImage(os);
		session.setAttribute("imageCode", captcha);
		os.flush();
		os.close();
	}

	@RequestMapping("/user/get_user_detail")
	@ResponseBody
	public Operator queryUserDetail(HttpServletRequest request, HttpServletResponse res, String optNo) {
		BaseResult1 result = new BaseResult1();
		if (StringUtils.isBlank(optNo)) {
			result.setRet(BaseResult1.BIZ_ERROR);
			result.setMsg("登录名不能为空");
			RestUtils.error(res, result);
			return null;
		}
		try {
			Operator operator = userMgMtService.getUserDetail(optNo);
			if (operator != null) {
				return operator;
			} else {
				result.setRet(BaseResult1.BIZ_ERROR);
				result.setMsg("未查询到用户信息");
				RestUtils.error(res, result);
				return null;
			}
		} catch (Throwable t) {
			result.setRet(BaseResult1.SYS_ERROR);
			result.setMsg("获取用户信息失败");
			RestUtils.error(res, result);
			return null;
		}
	}
	
	/**
	 * 用户角色信息查询
	 * 
	 * @param request
	 * @param pageCount
	 * @return
	 */
	@RequestMapping(value = "/roles/query_user_roles")
	@ResponseBody
	public PageCount queryUserRoles(HttpServletRequest request, PageCount pageCount) {
		// String optNo = (String) request.getSession().getAttribute("optNo");
		PageCount pageQuery = userMgMtService.queryUserRoles(pageCount);
		return pageQuery;

	}
	/**
	 * 用户退出系统
	 * 
	 * @param request
	 * @param pageCount
	 * @return
	 */
	@RequestMapping(value = "/user/quit_user_ope")
	@ResponseBody
	public BaseResult1 quitUserOpe(HttpServletRequest request, HttpServletResponse res) {
		BaseResult1 result = new BaseResult1();
		request.getSession().invalidate();
		result.setMsg(BaseResult1.SUCCESS);
		return result;
	}
	/**
	 * 获取枚举类型
	 * 
	 * @param request
	 * @param pageCount
	 * @return
	 */
	@RequestMapping(value = "/user/get_enum_info")
	@ResponseBody
	public List<Enum> getEnumInfo(HttpServletRequest request, HttpServletResponse res,String enumType) {
		if(StringUtils.isBlank(enumType)){
			BaseResult1 result=new BaseResult1();
			result.setRet(BaseResult1.BIZ_ERROR);
			result.setMsg("枚举类型不能为空");
			RestUtils.error(res, result);
			return null;
		}
		List<Enum> enumInfo = userMgMtService.queryEnumInfo(enumType);
		return enumInfo;
	}
	/**
	 * @Title: modifyUserPwd
	 * @Description: 修改用户密码
	 * @param operator
	 * @return
	 * @author hui
	 * @date: 2016年12月22日 上午10:02:24
	 */
	@RequestMapping("/user/modify_user_pwd")
	@ResponseBody
	public BaseResult1 modifyUserPwd(HttpServletRequest req, HttpServletResponse res,Operator operator,char[] oldPwd,char[] confirmPwd){
		BaseResult1 baseResult=new BaseResult1();
		if(null == oldPwd || StringUtils.isBlank(String.valueOf(oldPwd))){
			baseResult.setRet(BaseResult1.BIZ_ERROR);
			baseResult.setMsg("原密码不能为空");
			RestUtils.error(res, baseResult);
			return null;
		}
		if(null == oldPwd || StringUtils.isBlank(String.valueOf(operator.getOptPassword()))){
			baseResult.setRet(BaseResult1.BIZ_ERROR);
			baseResult.setMsg("新密码不能为空");
			RestUtils.error(res, baseResult);
			return null;
		}
		if(null == confirmPwd || StringUtils.isBlank(String.valueOf(confirmPwd))){
			baseResult.setRet(BaseResult1.BIZ_ERROR);
			baseResult.setMsg("确认密码不能为空");
			RestUtils.error(res, baseResult);
			return null;
		}
		if(Arrays.equals(operator.getOptPassword(), oldPwd)){
			baseResult.setRet(BaseResult1.BIZ_ERROR);
			baseResult.setMsg("新密码和原密码不可以相同");
			RestUtils.error(res, baseResult);
			return null;
		}
		if(!Arrays.equals(operator.getOptPassword(), confirmPwd)){
			baseResult.setRet(BaseResult1.BIZ_ERROR);
			baseResult.setMsg("新密码和确认密码不一致");
			RestUtils.error(res, baseResult);
			return null;
		}
		UserSessionBo userSessionBo = (UserSessionBo) req.getSession().getAttribute("user");
		Operator valOpe = userMgMtService.selectByOptnoAndPwd(userSessionBo.getOptNo(), oldPwd);
		if(valOpe==null){
			baseResult.setRet(BaseResult1.BIZ_ERROR);
			baseResult.setMsg("原始密码输入有误，请修改");
			RestUtils.error(res, baseResult);
			return null;
		}
		operator.setOptNo(userSessionBo.getOptNo());
		operator.setOptPassword(PasswordHashUtil.createHash(operator.getOptPassword()).toCharArray());
		operator.setMdfUser(userSessionBo.getOptNo());
		operator.setMdfDate(new Date());
		int row = userMgMtService.modifyUserPwd(operator);
		if(row>0){
			baseResult.setRet(BaseResult1.SUCCESS);
			baseResult.setMsg("密码修改成功");
			return baseResult;
		}else {
			baseResult.setRet(BaseResult1.BIZ_ERROR);
			baseResult.setMsg("密码修改失败");
			RestUtils.error(res, baseResult);
			return null;
		}
	}
	@RequestMapping(value = "/user/get_user_type")
	@ResponseBody
	public List<Enum> getEnumInfo(HttpServletRequest request) {
		List<Enum> optTtypeList= userMgMtService.queryOptType();
		return optTtypeList;
	}
	
	
	
	
//	public static void main(String[] args) {
//		String pwd=PasswordHashUtil.createHash("admin".toCharArray());//将密码加密
//		log.info(pwd);
//	}
}
